<template>
    <div>
        <el-button type="primary" @click="createServe">刷新</el-button>
        <el-button type="primary" @click="destoryServe">关闭</el-button>
        <ul>
            <li v-for="(item, index) in msgList" :key="index">
                <el-row>
                    <el-col :span="12">ID：{{item.id}}</el-col>
                    <el-col :span="12">名称：{{item.name}}</el-col>
                </el-row>
            </li>
        </ul>
    </div>
</template>

<script>
let client = null
export default {
    data() {
        return {
            msgList: []
        };
    },
    mounted() {
        client = this.createServe();
        console.log(client instanceof WebSocket);
    },
    methods: {
        createServe() {
            this.destoryServe()
            // const ws = new WebSocket('ws://192.168.73.222:58587/wiv/socket/223');
            const ws = new WebSocket('ws://192.168.73.123:8080/', ['echo-protocol']);

            ws.onerror = () => {
                console.log('连接错误');
            };

            ws.onopen = () => {
                console.log('连接成功');

                ws.send('发送测试消息');
            };

            ws.onclose = () => {
                console.log('连接关闭');
            };

            ws.onmessage = (e) => {
                console.log('接受消息: ' + e.data);
                if (typeof e.data === 'string') {
                    this.msgList = JSON.parse(e.data)
                }
            };

            return ws
        },
        destoryServe() {
            if (client instanceof WebSocket) {
                client.close()
                client = null
            }
        }
    }
};
</script>

<style lang="scss" scoped>
ul{
    list-style: none;
    max-width: 600px;
    margin: 60px auto 0;
    li{
        list-style: none;
        padding: 16px;
        border: 1px solid #8e8e8e;
        border-radius: 4px;
        & + li{
            margin-top: 8px;
        }
    }
}
</style>
